package list

import "fmt"

type MyLinkedList struct {
	Val  int
	Next *MyLinkedList
}

func Constructor707() MyLinkedList {
	return MyLinkedList{0, nil}
}

func (this *MyLinkedList) Get(index int) int {
	i := 0
	node := this.Next
	for i != index && node != nil {
		i++
		node = node.Next
	}

	if node == nil {
		return -1
	} else {
		return node.Val
	}
}

func (this *MyLinkedList) AddAtHead(val int) {
	temp := MyLinkedList{
		Val:  val,
		Next: this.Next,
	}

	this.Next = &temp

}

func (this *MyLinkedList) AddAtTail(val int) {
	node := this.Next
	for node.Next != nil {
		node = node.Next
	}
	node.Next = &MyLinkedList{val, nil}
}

func (this *MyLinkedList) AddAtIndex(index int, val int) {
	i := -1
	node := this
	for i != index-1 && node != nil {
		node = node.Next
		i++
	}

	if i+1 > index || node == nil {
		return
	}

	temp := &MyLinkedList{val, nil}
	if node.Next == nil {
		node.Next = temp
	} else {
		temp.Next = node.Next
		node.Next = temp
	}

}

func (this *MyLinkedList) DeleteAtIndex(index int) {
	i := -1
	node := this

	for i != index-1 && node != nil {
		node = node.Next
		i++
	}

	if node != nil && node.Next != nil {
		node.Next = node.Next.Next
	}
}

func (this *MyLinkedList) PrintMyLink() {
	temp := this.Next
	for temp != nil {
		fmt.Printf("%d  ", temp.Val)
		temp = temp.Next
	}
	fmt.Println()
}
